package main

import (
	"bufio"
	"errors"
	"fmt"
	"html/template"
	"log"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

var CURR_PATH = "/Users/peishuaishuai/workbench/ant-learn-go/p026_simple_body_weight_manager"

// 体重按天记录
type BodyWeight struct {
	Pdate  string
	Weight float64
}

// 读取文件数据到日期体重列表
func readFileToBodyWeights(fileName string) ([]BodyWeight, error) {
	var bodyWeights []BodyWeight
	file, err := os.Open(fileName)
	if err != nil {
		return bodyWeights, err
	}

	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		fields := strings.Split(line, ",")
		if len(fields) != 2 {
			return bodyWeights, errors.New("错误，出现了错误的数据行: " + line)
		}

		pdate := fields[0]
		bodyWeight, err := strconv.ParseFloat(fields[1], 64)
		if err != nil {
			return bodyWeights, errors.New("错误，出现了体重不是小数的数据行: " + line)
		}

		bodyWeights = append(bodyWeights,
			BodyWeight{Pdate: pdate, Weight: bodyWeight})
	}

	if scanner.Err() != nil {
		return bodyWeights, scanner.Err()
	}

	return bodyWeights, nil
}

func main() {

	http.HandleFunc("/show", showAllWeights)
	http.HandleFunc("/addWeight", addWeight)
	http.HandleFunc("/doCreate", doCreate)

	// 启动web服务
	err := http.ListenAndServe("0.0.0.0:8888", nil)
	log.Fatal(err)
}

// 接收提交体重的参数
func doCreate(writer http.ResponseWriter, request *http.Request) {
	weight := request.FormValue("weight")
	weightNumber, err := strconv.ParseFloat(weight, 64)
	if err != nil {
		_, err := writer.Write([]byte("错误，weight应该是一个数字"))
		if err != nil {
			panic(err)
		}
	}
	year, month, day := time.Now().Date()
	pdate := fmt.Sprintf("%d-%02d-%02d", year, month, day)

	file, err := os.OpenFile(CURR_PATH+"/data_body_weights.txt",
		os.O_WRONLY|os.O_APPEND, os.FileMode(0700))
	if err != nil {
		panic("读取文件失败")
	}

	_, err = file.WriteString(fmt.Sprintf("%s,%f\n", pdate, weightNumber))
	if err != nil {
		panic(err)
	}

	err = file.Close()
	if err != nil {
		panic(err)
	}

	http.Redirect(writer, request, "/show", http.StatusFound)
}

// 添加新的体重
func addWeight(writer http.ResponseWriter, request *http.Request) {
	tpl, _ := template.ParseFiles(CURR_PATH + "/addWeight.html")
	tpl.Execute(writer, nil)
}

func showAllWeights(writer http.ResponseWriter, request *http.Request) {
	fileName := CURR_PATH + "/data_body_weights.txt"
	bodyWeights, err := readFileToBodyWeights(fileName)
	if err != nil {
		log.Fatal("读取体重文件错误")
	}

	fmt.Printf("%#v", bodyWeights)

	tpl, _ := template.ParseFiles(CURR_PATH + "/showAllWeights.html")
	err = tpl.Execute(writer, bodyWeights)
	if err != nil {
		log.Fatal("模板渲染从出错" + err.Error())
	}
}
